package cn.how2go.api.controller;


import cn.how2go.api.common.*;
import cn.how2go.api.entity.*;
import cn.how2go.api.service.*;
import cn.how2go.api.util.DateUtil;
import cn.how2go.api.util.GPSTransToAMap;
import cn.how2go.api.vo.DeviceUserVo;
import cn.how2go.api.vo.FenceVo;
import cn.how2go.api.vo.PageVo;
import cn.how2go.api.vo.Userids;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.beans.PersistenceDelegate;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author LGP
 * @since 2020-05-31
 */
@Api(value = "设备",description = "设备信息的管理")
@RestController
@RequestMapping("/api/device")
public class DeviceController {

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private PositionService positionService;

    @Autowired
    private WellnessService wellnessService;

    @Autowired
    private WarningService warningService;

    @Autowired
    private PersonService personService;

    @Autowired
    private UserInfoService userInfoService;

    @ApiOperation(value="分页查询人员状态列表", notes="")
    @RequestMapping(value = "pageUserState", method = RequestMethod.POST)
    public Pagination pageUserState(@RequestBody PageParam param){
        Pagination<UserState> pagination = new Pagination<>(param.getPage(),param.getSize(),null,null);
        List<UserState> all = allUserState();
        //共有数据量
        Integer count = all.size();
        //算出共有多少页
        Integer total = (count%param.getSize()==0)?count/param.getSize():count/param.getSize()+1;
        pagination.setTotal(total);
        //当前页的数据
        List<UserState> result = new ArrayList<>();
        //开始取数据的标记
        Integer offset = pagination.offset();
        if((offset+param.getSize())>all.size()) {
            for (int i = offset; i < all.size(); i++) {
                result.add(all.get(i));
            }
        }else{
            for (int i = offset; i < offset+param.getSize(); i++) {
                result.add(all.get(i));
            }
        }
        pagination.setItems(result);
        return pagination;
    }

    @ApiOperation(value="分页查询人员设备状态列表", notes="")
    @RequestMapping(value = "pageUserDevice", method = RequestMethod.POST)
    public Pagination pageUserDevice(@RequestBody PageParam param){
        Pagination<UserDeviceState> pagination = new Pagination<>(param.getPage(),param.getSize(),null,null);
        List<UserDeviceState> all = allUserDeviceState();
        //共有数据量
        Integer count = all.size();
        //算出共有多少页
        Integer total = (count%param.getSize()==0)?count/param.getSize():count/param.getSize()+1;
        pagination.setTotal(total);
        //当前页的数据
        List<UserDeviceState> result = new ArrayList<>();
        //开始取数据的标记
        Integer offset = pagination.offset();
        if((offset+param.getSize())>all.size()) {
            for (int i = offset; i < all.size(); i++) {
                result.add(all.get(i));
            }
        }else{
            for (int i = offset; i < offset+param.getSize(); i++) {
                result.add(all.get(i));
            }
        }
        pagination.setItems(result);
        return pagination;
    }

    @ApiOperation(value="查询人员设备状态列表", notes="")
    @RequestMapping(value = "listUserDevice", method = RequestMethod.GET)
    public CommonResult listUserDevice(){
        List<UserDeviceState> result = new ArrayList<>();
        result = allUserDeviceState();
        return CommonResult.success(result);
    }

    private List<UserState> allUserState(){
        List<UserState> result = new ArrayList<>();
        //获取所有帽子设备信息
        EntityWrapper<Device> maoew = new EntityWrapper<>();
        maoew.eq("type",1);
        maoew.ne("state",4);
        List<Device> listMao = deviceService.selectList(maoew);
        //转化为Map
        Map<String,Device> maoIdKey = new HashMap<>();
        Map<String,Device> maoUserKey = new HashMap<>();
        for(Device device:listMao){
            maoIdKey.put(device.getId(),device);
            if(device.getOwner()!=null && !device.getOwner().equals("")){
                maoUserKey.put(device.getOwner(),device);
            }
        }
        //先查询所有人员
        //TODO:
        List<UserInfo> userInfos = userInfoService.listUserInfo();
        for(UserInfo person:userInfos){
            UserState bean = new UserState();
            bean.setId(person.getId());
            bean.setName(person.getName());
            bean.setRole(person.getRole());
            bean.setState(0);
            Device maoDevice = maoUserKey.get(person.getId());
            if(maoDevice!=null){
                bean.setState(maoDevice.getWorking());
            }
            result.add(bean);
        }
        return result;
    }

    private List<UserDeviceState> allUserDeviceState(){
        List<UserDeviceState> result = new ArrayList<>();
        //获取所有帽子设备信息
        EntityWrapper<Device> maoew = new EntityWrapper<>();
        maoew.eq("type",1);
        //maoew.ne("state",3);
        List<Device> listMao = deviceService.selectList(maoew);
        //转化为Map
        Map<String,Device> maoIdKey = new HashMap<>();
        Map<String,Device> maoUserKey = new HashMap<>();
        for(Device device:listMao){
            maoIdKey.put(device.getId(),device);
            if(device.getOwner()!=null && !device.getOwner().equals("")){
                maoUserKey.put(device.getOwner(),device);
            }
        }

        //获取所有手环设备信息
        EntityWrapper<Device> shouew = new EntityWrapper<>();
        shouew.eq("type",2);
        shouew.ne("state",4);
        List<Device> listShou = deviceService.selectList(shouew);
        //转化为Map
        Map<String,Device> shouIdKey = new HashMap<>();
        Map<String,Device> shouUserKey = new HashMap<>();
        for(Device device:listShou){
            shouIdKey.put(device.getId(),device);
            if(device.getOwner()!=null && !device.getOwner().equals("")){
                shouUserKey.put(device.getOwner(),device);
            }
        }
        //先查询所有人员
        //TODO:
        List<UserInfo> userInfos = userInfoService.listUserInfo();
        for(UserInfo person:userInfos){
            UserDeviceState bean = new UserDeviceState();
            bean.setId(person.getId());
            bean.setName(person.getName());
            bean.setRole(person.getRole());
            bean.setPhone(person.getPhone());
            bean.setState(0);
            bean.setWarring(0);
            Device maoDevice = maoUserKey.get(person.getId());

            if(maoDevice!=null){
                bean.setMaoDevice(maoDevice.getId());
                bean.setMaoState(1);
                if(maoDevice.getState() ==2){
                    if(maoDevice.getWorking() == 1)
                        bean.setMaoState(2);
                }

                bean.setMaoSn(maoDevice.getTermID());

                bean.setMaoWorking(maoDevice.getWorking());
                bean.setMaoLastTime(maoDevice.getLastTime());
                //System.out.println("安全帽ID=="+maoDevice.getId());
                Position position = this.getMaxTimeRecodePosition(maoDevice.getId());
                if(position!=null){
                    bean.setLon(position.getLon());
                    bean.setLat(position.getLat());
                    bean.setLon2(position.getLon2());
                    bean.setLat2(position.getLat2());
                    bean.setAlt(position.getAlt());
                    bean.setHeight(position.getHeight());
                    bean.setRecordTime(position.getRecordTime());

                }
                //获取未处理告警信息
                setWarnningList(bean,maoDevice.getId());
            }

            Device shouDevice = shouUserKey.get(person.getId());
            if(shouDevice!=null){
                bean.setShouDevice(shouDevice.getId());
//                Wellness wellness = this.getMaxTimeRecodeWell(shouDevice.getId());
//                if(wellness!=null){
//                    bean.setSystolic(wellness.getSystolic());
//                    bean.setDiastolic(wellness.getDiastolic());
//                    bean.setPulse(wellness.getPulse());
//                    bean.setTemp(wellness.getTemp());
//                }
                bean.setSystolic(person.getSystolic());
                bean.setDiastolic(person.getDiastolic());
                bean.setPulse(person.getPulse());
                bean.setTemp(person.getTemp());
                List<Date> dates = new ArrayList<>();
                if(person.getTempTime()!=null){
                    dates.add(person.getTempTime());
                }
                if(person.getDiastolicTime()!=null){
                    dates.add(person.getDiastolicTime());
                }
                if(person.getSystolicTime()!=null){
                    dates.add(person.getSystolicTime());
                }
                if(person.getPulseTime()!=null){
                    dates.add(person.getPulseTime());
                }
                Date tdate = DateUtil.getMaxDate(dates);
                bean.setTempLastTime(tdate);
                setWarnningList(bean,shouDevice.getId());
            }
            result.add(bean);
        }
//        EntityWrapper<Person> pew = new EntityWrapper<>();
//        List<Person> listPerson = personService.selectList(pew);
//        //遍历人员信息，创建人员状态信息表
//        for(Person person:listPerson){
//            UserDeviceState bean = new UserDeviceState();
//            bean.setId(person.getId());
//            bean.setName(person.getName());
//            bean.setRole(person.getRole());
//            bean.setPhone(person.getPhone());
//            bean.setState(0);
//            bean.setWarring(0);
//            Device maoDevice = maoUserKey.get(person.getId());
//            if(maoDevice!=null){
//                bean.setMaoDevice(maoDevice.getId());
//                bean.setState(maoDevice.getWorking());
//                bean.setMaoSn(maoDevice.getTermID());
//                bean.setMaoState(maoDevice.getState());
//                bean.setMaoWorking(maoDevice.getWorking());
//                bean.setMaoLastTime(maoDevice.getLastTime());
//                Position position = this.getMaxTimeRecodePosition(maoDevice.getId());
//                if(position!=null){
//                    bean.setLon(position.getLon());
//                    bean.setLat(position.getLat());
//                    bean.setLon2(position.getLon2());
//                    bean.setLat2(position.getLat2());
//                    bean.setAlt(position.getAlt());
//                    bean.setRecordTime(position.getRecordTime());
//
//                }
//                //获取未处理告警信息
//                setWarnningList(bean,maoDevice.getId());
//            }
//            Device shouDevice = shouUserKey.get(person.getId());
//            if(shouDevice!=null){
//                bean.setShouDevice(shouDevice.getId());
//                Wellness wellness = this.getMaxTimeRecodeWell(shouDevice.getId());
//                if(wellness!=null){
//                    bean.setSystolic(wellness.getSystolic());
//                    bean.setDiastolic(wellness.getDiastolic());
//                    bean.setPulse(wellness.getPulse());
//                    bean.setTemp(wellness.getTemp());
//                }
//                setWarnningList(bean,shouDevice.getId());
//            }
//            result.add(bean);
//        }

        return result;
    }

    private void setWarnningList(UserDeviceState bean,String device){
        //获取未处理告警信息
        EntityWrapper<Warning> warningEntityWrapper = new EntityWrapper<>();
        warningEntityWrapper.eq("device",device);
        warningEntityWrapper.eq("state",0);
        List<Warning> warringLists = warningService.selectList(warningEntityWrapper);
        if(warringLists!=null&& warringLists.size()>0){
            bean.setWarring(bean.getWarring()+warringLists.size());
            List<Integer> wl = bean.getWarringList()!=null?bean.getWarringList():new ArrayList<>();
            for (Warning warning:warringLists){
                wl.add(warning.getType());
            }
            bean.setWarringList(wl);
        }
    }

    private Position getMaxTimeRecodePosition(String id){
        EntityWrapper<Position> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("Device",id);
        entityWrapper.orderBy("RecordTime",false);
        entityWrapper.last("limit 1");
        Position bean = positionService.selectOne(entityWrapper);
        return bean;
    }

    private Wellness getMaxTimeRecodeWell(String id){
        EntityWrapper<Wellness> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("Device",id);
        entityWrapper.orderBy("RecordTime",false);
        entityWrapper.last("limit 1");
        Wellness bean = wellnessService.selectOne(entityWrapper);
        return bean;
    }


    @ApiOperation(value="查询设备信息列表", notes="")
    @RequestMapping(value = "listDevice", method = RequestMethod.GET)
    public CommonResult listDevice(){
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.orderBy("CreateTime",false);
        List<Device> list = deviceService.selectList(entityWrapper);
        return CommonResult.success(list);
    }

    @ApiOperation(value="查询设备详细信息列表", notes="")
    @RequestMapping(value = "listDeviceUser", method = RequestMethod.GET)
    private CommonResult listDeviceUser(){
        List<DeviceUserVo> list = new ArrayList<>();
        //查询所有设备信息
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.ne("state",4);
        entityWrapper.orderBy("CreateTime",false);
        List<Device> allDevice = deviceService.selectList(entityWrapper);
        //查询人员信息
        EntityWrapper<Person> personEntityWrapper = new EntityWrapper<>();
        personEntityWrapper.orderBy("CreateTime",false);
        List<Person> listPerson = personService.selectList(personEntityWrapper);
        //List转换为Map
        Map<String, Person> mapPerson = new HashMap<>();
        for(Person person:listPerson){
            mapPerson.put(person.getId(),person);
        }
        //创建设备详细信息
        for(Device device:allDevice){
            DeviceUserVo bean = new DeviceUserVo();
            bean.setId(device.getId());
            bean.setTermId(device.getTermID());
            bean.setType(device.getType());
            String own = device.getOwner();
            if(own!=null &&!own.equals("")) {
                bean.setOwnerId(own);
                Person person = mapPerson.get(own);
                bean.setOwnerName(person.getName());
                bean.setOwnerRole(person.getRole());
            }
            bean.setFenceId("");
            list.add(bean);
        }

        return CommonResult.success(list);
    }

    @ApiOperation(value="保存设备信息", notes="初始添加一个新设备，LastTime，CreateTime后台生成")
    @RequestMapping(value = "saveDevice", method = RequestMethod.POST)
    public CommonResult saveDevice(@RequestBody Device device){
        //验证
        if(device.getTermID()==null || device.getTermID().trim().equals("")){
            return CommonResult.fail("设备编号不能为空");
        }

        if(device.getType()==null){
            return CommonResult.fail("设备类型不能为空");
        }

        EntityWrapper<Device> entityWrapper1 = new EntityWrapper<>();
        entityWrapper1.eq("TermID",device.getTermID());
        entityWrapper1.eq("type",device.getType());
        List<Device> list1 = deviceService.selectList(entityWrapper1);
        if(list1!=null && list1.size()>0){
            return CommonResult.fail("设备编号已存在");
        }


        if(device.getOwner()==null || device.getOwner().trim().equals("")){
            return CommonResult.fail("绑定人员不能为空");
        }

        EntityWrapper<Device> entityWrapper2 = new EntityWrapper<>();
        entityWrapper2.eq("owner",device.getOwner());
        entityWrapper2.eq("Type",device.getType());
        entityWrapper2.ne("TermID","");
        List<Device> list2 = deviceService.selectList(entityWrapper2);
        if(list2!=null && list2.size()>0){
            return CommonResult.fail("此人员已经存在此类型设备");
        }

        device.setId(UUID.randomUUID().toString());
        device.setLastTime(new Date());
        device.setCreateTime(new Date());
        boolean flag = deviceService.insert(device);
        if(!flag){
            return CommonResult.fail("保存失败");
        }
        return CommonResult.success(device);
    }

    @ApiOperation(value="修改设备信息", notes="修改设备信息，LastTime后台修改")
    @RequestMapping(value = "editDevice", method = RequestMethod.POST)
    public CommonResult editDevice(@RequestBody Device device){
        if(device.getTermID()==null || device.getTermID().trim().equals("")){
            return CommonResult.fail("设备编号不能为空");
        }
        if(device.getType()==null){
            return CommonResult.fail("设备类型不能为空");
        }

        if(device.getOwner()==null || device.getOwner().trim().equals("")){
            return CommonResult.fail("绑定人员不能为空");
        }
        EntityWrapper<Device> entityWrapper1 = new EntityWrapper<>();
        entityWrapper1.ne("ID",device.getId());
        entityWrapper1.eq("type",device.getType());
        entityWrapper1.eq("TermID",device.getTermID());
        List<Device> list1 = deviceService.selectList(entityWrapper1);
        if(list1!=null && list1.size()>0){
            return CommonResult.fail("设备编号已存在");
        }

        EntityWrapper<Device> entityWrapper2 = new EntityWrapper<>();
        entityWrapper2.ne("ID",device.getId());
        entityWrapper2.eq("owner",device.getOwner());
        entityWrapper2.eq("Type",device.getType());
        entityWrapper2.ne("TermID","");
        List<Device> list2 = deviceService.selectList(entityWrapper2);
        if(list2!=null && list2.size()>0){
            return CommonResult.fail("此人员已经存在此类型设备");
        }

        device.setLastTime(new Date());
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",device.getId());
        boolean flag = deviceService.update(device,entityWrapper);
        if(!flag){
            return CommonResult.fail("修改失败");
        }
        return CommonResult.success(device);
    }

    @ApiOperation(value="删除设备信息", notes="删除设备信息，LastTime后台修改")
    @RequestMapping(value = "deleteDevice", method = RequestMethod.GET)
    public MessageResult deleteDevice(@RequestParam String id){
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",id);
        Device param = new Device();
        param.setState(4);
        param.setTermID("");
        param.setOwner("");
        deviceService.update(param,entityWrapper);
        return MessageResult.getSuccess("删除成功");
    }

    @ApiOperation(value="获取设备", notes="根据ID获取设备")
    @RequestMapping(value = "getDeviceByTermID",method = {RequestMethod.POST,RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "TermID", value = "设备的终端唯一编号", required = true, dataType = "String"),
    })
    public CommonResult getDeviceByTermID(@RequestParam(value = "TermID") String TermID){
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("TermID",TermID);
        entityWrapper.last("limit 1");
        Device device = deviceService.selectOne(entityWrapper);
        if(device == null){
            return CommonResult.fail("获取失败");
        }
        return CommonResult.success(device);
    }

    @ApiOperation(value="判断人员设备是否存在", notes="")
    @RequestMapping(value = "findDeviceUser",method = {RequestMethod.GET})
    @ApiImplicitParams({
        @ApiImplicitParam(paramType="query", name = "type", value = "设备类型", required = true, dataType = "Integer"),
        @ApiImplicitParam(paramType="query", name = "owner", value = "绑定人员", required = true, dataType = "String"),
    })
    public CommonResult findDeviceUser(@RequestParam Integer type,@RequestParam String owner) {
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("type", type);
        entityWrapper.eq("owner", owner);
        entityWrapper.ne("TermID","");
        entityWrapper.last("limit 1");
        Device device = deviceService.selectOne(entityWrapper);
        if (device == null) {
            return CommonResult.fail("获取失败");
        }
        return CommonResult.success(device);
    }

    @ApiOperation(value="获取设备", notes="根据终端唯一编号获取设备")
    @RequestMapping(value = "getDevice",method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "type", value = "设备类型", required = true, dataType = "Integer"),
            @ApiImplicitParam(paramType="query", name = "termId", value = "UUID", required = true, dataType = "String"),
    })
    public CommonResult getDevice(@RequestParam(value = "termId") String termId,@RequestParam Integer type){
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("TermID",termId);
        entityWrapper.eq("type",type);
        entityWrapper.last("limit 1");
        Device device = deviceService.selectOne(entityWrapper);
        if(device == null){
            return CommonResult.fail("获取失败");
        }
        return CommonResult.success(device);
    }

    @ApiOperation(value="获取设备", notes="根据终端唯一编号获取设备")
    @RequestMapping(value = "getDeviceById",method = {RequestMethod.GET})
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "ID", value = "UUID", required = true, dataType = "String"),
    })
    public CommonResult getDeviceById(@RequestParam(value = "ID") String id){
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("ID",id);
        entityWrapper.last("limit 1");
        Device device = deviceService.selectOne(entityWrapper);
        if(device == null){
            return CommonResult.fail("获取失败");
        }
        return CommonResult.success(device);
    }

    @ApiOperation(value="绑定设备人员信息", notes="")
    @RequestMapping(value = "bindDeviceOwner", method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(paramType="query", name = "TermID", value = "设备的终端唯一编号", required = true, dataType = "String"),
            @ApiImplicitParam(paramType="query", name = "Owner", value = "此设备绑定人员的ID", required = true, dataType = "String"),
    })
    public CommonResult bindDeviceOwner(
            @RequestParam(value = "TermID", required = true) String TermID,
            @RequestParam(value = "Owner", required = true) String Owner){
        Device device = new Device();
        device.setOwner(Owner);
        EntityWrapper<Device> entityWrapper = new EntityWrapper<>();
        entityWrapper.eq("TermID",TermID);
        boolean flag = deviceService.update(device,entityWrapper);
        if(!flag){
            return CommonResult.fail("绑定失败");
        }
        return CommonResult.success(device);
    }

    @ApiOperation(value="人员详细信息", notes="")
    @RequestMapping(value = "getListUserInfo", method = RequestMethod.GET)
    public CommonResult getListUserInfo(){
        List<UserInfo> userInfos = userInfoService.listUserInfo();
        return CommonResult.success(userInfos);
    }

    @ApiOperation(value="人员详细状态", notes="根据ID获取人员详细状态")
    @RequestMapping(value = "getUserStateById",method = {RequestMethod.POST,RequestMethod.GET})
    public CommonResult getUserStateById(@RequestParam(value = "ID") String id){
        UserDeviceState bean = new UserDeviceState();
        bean.setState(0);
        //获取所有帽子设备信息
        EntityWrapper<Device> maoew = new EntityWrapper<>();
        maoew.eq("type",1);
        maoew.eq("owner", id);
        List<Device> listMao = deviceService.selectList(maoew);

        //获取所有手环设备信息
        EntityWrapper<Device> shouew = new EntityWrapper<>();
        shouew.eq("type",2);
        shouew.eq("owner", id);
        List<Device> listShou = deviceService.selectList(shouew);

        //先查询所有人员
        Person person = userInfoService.selectUserInfoOnce(id);

        bean.setId(person.getId());
        bean.setName(person.getName());
        bean.setRole(person.getRole());
        bean.setPhone(person.getPhone());
        bean.setState(0);
        bean.setWarring(0);
        if(listMao!=null && listMao.size()!=0) {
            Device maoDevice = listMao.get(0);
            bean.setMaoDevice(maoDevice.getId());
            bean.setState(maoDevice.getWorking());
            bean.setMaoSn(maoDevice.getTermID());
            bean.setMaoState(maoDevice.getState());
            bean.setMaoWorking(maoDevice.getWorking());
            bean.setMaoLastTime(maoDevice.getLastTime());
            Position position = this.getMaxTimeRecodePosition(maoDevice.getId());
            if(position!=null){
                bean.setLon(position.getLon());
                bean.setLat(position.getLat());
                bean.setLon2(position.getLon2());
                bean.setLat2(position.getLat2());
                bean.setAlt(position.getAlt());
                bean.setHeight(position.getHeight());
                bean.setRecordTime(position.getRecordTime());
            }
            //获取未处理告警信息
            setWarnningList(bean,maoDevice.getId());
        }


        return CommonResult.success(bean);
    }

    @RequestMapping(value = "nowUserState", method = RequestMethod.POST)
    public CommonList<UserDeviceState> nowUserState(@RequestBody Userids userids){
        List<UserDeviceState> result = idsUserDeviceState(userids.getIds());
        return CommonList.success(result);
    }

    private List<UserDeviceState> idsUserDeviceState(String ids){
        List<UserDeviceState> result = new ArrayList<>();
        //获取所有帽子设备信息
        EntityWrapper<Device> maoew = new EntityWrapper<>();
        maoew.eq("type",1);
        //maoew.ne("state",3);
        List<Device> listMao = deviceService.selectList(maoew);
        //转化为Map
        Map<String,Device> maoIdKey = new HashMap<>();
        Map<String,Device> maoUserKey = new HashMap<>();
        for(Device device:listMao){
            maoIdKey.put(device.getId(),device);
            if(device.getOwner()!=null && !device.getOwner().equals("")){
                maoUserKey.put(device.getOwner(),device);
            }
        }

        //获取所有手环设备信息
        EntityWrapper<Device> shouew = new EntityWrapper<>();
        shouew.eq("type",2);
        shouew.ne("state",4);
        List<Device> listShou = deviceService.selectList(shouew);
        //转化为Map
        Map<String,Device> shouIdKey = new HashMap<>();
        Map<String,Device> shouUserKey = new HashMap<>();
        for(Device device:listShou){
            shouIdKey.put(device.getId(),device);
            if(device.getOwner()!=null && !device.getOwner().equals("")){
                shouUserKey.put(device.getOwner(),device);
            }
        }
        //先查询所有人员
        //TODO:
        List<UserInfo> userInfos = userInfoService.listUserInfos(ids);
        for(UserInfo person:userInfos){
            UserDeviceState bean = new UserDeviceState();
            bean.setId(person.getId());
            bean.setName(person.getName());
            bean.setRole(person.getRole());
            bean.setPhone(person.getPhone());
            bean.setState(0);
            bean.setWarring(0);
            Device maoDevice = maoUserKey.get(person.getId());
            if(maoDevice!=null){
                bean.setState(maoDevice.getWorking());
            }
            if(maoDevice!=null){
                bean.setMaoDevice(maoDevice.getId());
                bean.setMaoState(1);
                if(maoDevice.getState() ==2){
                    if(maoDevice.getWorking() == 1)
                        bean.setMaoState(2);
                }

                bean.setMaoSn(maoDevice.getTermID());
                bean.setState(maoDevice.getWorking());
                bean.setMaoWorking(maoDevice.getWorking());
                bean.setMaoLastTime(maoDevice.getLastTime());
                //System.out.println("安全帽ID=="+maoDevice.getId());
                Position position = this.getMaxTimeRecodePosition(maoDevice.getId());
                if(position!=null){
                    bean.setLon(position.getLon());
                    bean.setLat(position.getLat());
                    bean.setLon2(position.getLon2());
                    bean.setLat2(position.getLat2());
                    bean.setAlt(position.getAlt());
                    bean.setHeight(position.getHeight());
                    bean.setRecordTime(position.getRecordTime());

                }
                //获取未处理告警信息
                setWarnningList(bean,maoDevice.getId());
            }

            Device shouDevice = shouUserKey.get(person.getId());
            if(shouDevice!=null){
                bean.setShouDevice(shouDevice.getId());

                bean.setSystolic(person.getSystolic());
                bean.setDiastolic(person.getDiastolic());
                bean.setPulse(person.getPulse());
                bean.setTemp(person.getTemp());
                List<Date> dates = new ArrayList<>();
                if(person.getTempTime()!=null){
                    dates.add(person.getTempTime());
                }
                if(person.getDiastolicTime()!=null){
                    dates.add(person.getDiastolicTime());
                }
                if(person.getSystolicTime()!=null){
                    dates.add(person.getSystolicTime());
                }
                if(person.getPulseTime()!=null){
                    dates.add(person.getPulseTime());
                }
                Date tdate = DateUtil.getMaxDate(dates);
                bean.setTempLastTime(tdate);
                setWarnningList(bean,shouDevice.getId());
            }
            result.add(bean);
        }


        return result;
    }
}

